package com.kawaiior.asoulworld.events;

import com.kawaiior.asoulworld.IdlFramework;
import com.kawaiior.asoulworld.capability.AsoulTimePower;
import com.kawaiior.asoulworld.capability.AvaPower;
import com.kawaiior.asoulworld.capability.CapabilityRegistryHandler;
import com.kawaiior.asoulworld.entity.creatures.misc.EntityBewilderedManProPlusMax;
import com.kawaiior.asoulworld.item.ModItems;
import com.kawaiior.asoulworld.potion.ModPotions;
import com.kawaiior.asoulworld.util.AsoulWorldUtils;
import com.kawaiior.asoulworld.util.EntityUtil;
import com.kawaiior.asoulworld.util.IDLGeneral;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.MobEffects;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

import java.util.List;

@Mod.EventBusSubscriber(modid = IdlFramework.MODID)
public class AsoulPlayerEvent {

    //玩家伤害生物
    @SubscribeEvent
    public static void AsoulPlayerAttackEvent(LivingHurtEvent event){
        Entity living = event.getSource().getTrueSource();
        if (!(living instanceof EntityPlayer) || living instanceof FakePlayer)
        {
            return;
        }

        EntityPlayer player = (EntityPlayer)living;
        EntityLivingBase hurtOne = event.getEntityLiving();
        World world = player.world;
        float amount = event.getAmount();

//        //propertyWeapon
//        if (player.getHeldItemMainhand().getItem() instanceof PropertyWeapon){
//            PropertyPower power = player.getHeldItemMainhand().getCapability(CapabilityRegistryHandler.PROPERTY_POWER, null);
//            for (int i = 0; i < power.getIproperties().length; i++) {
//                if (power.getIproperties()[i] == null) break;
//                power.getIproperties()[i].doProperty(event);
//            }
//        }

        //蓄意轰拳 嘉然套
        if(
                !player.getCooldownTracker().hasCooldown(ModItems.DIANA_HELMET) &&
                !player.isPotionActive(ModPotions.AS_OVER_LOAD) &&
                player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.DIANA_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.DIANA_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.DIANA_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.DIANA_BOOTS
        ){
            if (world.isRemote){
                EntityUtil.SpawnParticleAround(hurtOne, EnumParticleTypes.EXPLOSION_HUGE, 3);
            }else {
                event.setAmount(event.getAmount() * 3);
                EntityUtil.ApplyBuff(player, ModPotions.AS_OVER_LOAD, 0, 30f);
                EntityUtil.ApplyBuff(player, MobEffects.ABSORPTION, -4, 0f);

                player.getCooldownTracker().setCooldown(ModItems.DIANA_HELMET, 900);
                player.getCooldownTracker().setCooldown(ModItems.DIANA_CHESTPLATE, 900);
                player.getCooldownTracker().setCooldown(ModItems.DIANA_LEGGINGS, 900);
                player.getCooldownTracker().setCooldown(ModItems.DIANA_BOOTS, 900);
            }
            return;
        }

        if (world.isRemote){
            return;
        }

        // 珈乐 生命值越低伤害越高
        if (    player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.CAROL_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.CAROL_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.CAROL_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.CAROL_BOOTS
        ){
            event.setAmount(event.getAmount()*ASEventHelper.getCarolDamageMultiple(player.getHealth()));
            return;
        }

        // NaNaMi 对单伤害增加，对群有溅射效果 待定
        if (    player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.NANAMI_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.NANAMI_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.NANAMI_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.NANAMI_BOOTS
        ){
            if (event.getSource() instanceof EntityDamageSource){
                EntityDamageSource entityDamageSource = (EntityDamageSource) event.getSource();
                if (entityDamageSource.isMagicDamage()) {
                    return;
                }
            }
            float range = 4;
            Vec3d basePos = hurtOne.getPositionVector();
            List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, IDLGeneral.ServerAABB(basePos.addVector(-range, -range, -range), basePos.addVector(range, range, range)));
            if (entities.size() <= 2){
                event.getSource().setDamageBypassesArmor();
            }
            else {
                for (EntityLivingBase target : entities){
                    if (
                            target.isEntityEqual(player) ||
                            target.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem() == ModItems.AZI_HELMET ||
                            target.isEntityEqual(hurtOne)
                    ){
                        continue;
                    }
//                    target.attackEntityFrom(DamageSource.causePlayerDamage(player).setDamageBypassesArmor(), event.getAmount()*0.7f);
                    target.attackEntityFrom(DamageSource.causeIndirectMagicDamage(player, player), event.getAmount()*0.7f);
                }
                player.heal((entities.size()-2) * 0.8f);
                player.addPotionEffect(new PotionEffect(MobEffects.SPEED,160,0));
            }
            return;
        }

        // Azi
        if (    player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.AZI_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.AZI_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.AZI_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.AZI_BOOTS
        ){
            hurtOne.setFire(2);
            float h = event.getEntityLiving().getHealth();
            if (amount >= h || h <= 5f){
                event.setAmount(1000);
                event.getSource().setDamageBypassesArmor();
                player.heal(event.getEntityLiving().getHealth() * 0.5f);
                return;
            }
            float h2 = event.getEntityLiving().getMaxHealth();
            if (h2 < 40f) {
                event.setAmount(event.getAmount() * (h2 / 20f));
            }else {
                event.setAmount(event.getAmount()*2f);
            }
        }

        // Taffy
        if (    player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.TAFFY_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.TAFFY_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.TAFFY_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.TAFFY_BOOTS
        ){
            float ph = player.getHealth();
            float hm = event.getEntityLiving().getMaxHealth();
            float damage = (2f-(ph/21f))*amount + Math.max(hm * 0.1f, 3f);
            event.setAmount(damage);
        }
    }

    // 生物伤害玩家
    @SubscribeEvent
    public static void AsoulPlayerHutrEvent(LivingHurtEvent event){
        Entity entity = event.getSource().getTrueSource();
        EntityLivingBase hurtOne = event.getEntityLiving();

        if (!(hurtOne instanceof EntityPlayer)) return;
        EntityPlayer player = (EntityPlayer)hurtOne;
        World world = player.world;
        float amount = event.getAmount();
        float playerHealth = player.getHealth();

        if (world.isRemote){
            return;
        }

        // AvavaAva
        if (    player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.AVA_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.AVA_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.AVA_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.AVA_BOOTS
        ){
            AvaPower power = player.getCapability(CapabilityRegistryHandler.AVA_POWER, null);
            if (power == null){
                return;
            }
            if (!power.isHot()) {
                boolean flag = false;
                if (amount < 6 && amount<playerHealth) {
                    power.addPower(event.getAmount());
                    if (power.getPower() >= 15f) {
                        power.setPower(power.getPower() - 15f);
                        flag = true;
                    }
                } else {
                    flag = true;
                }
                if (flag){
                    power.setHot();
                    event.setAmount(0);
                    player.addPotionEffect(new PotionEffect(MobEffects.ABSORPTION, 0, -3));
                    player.addPotionEffect(new PotionEffect(ModPotions.AS_AVA_BUFF, 1200, 0));
                    player.getCooldownTracker().setCooldown(ModItems.AVA_HELMET, 1200);
                    player.getCooldownTracker().setCooldown(ModItems.AVA_CHESTPLATE, 1200);
                    player.getCooldownTracker().setCooldown(ModItems.AVA_LEGGINGS, 1200);
                    player.getCooldownTracker().setCooldown(ModItems.AVA_BOOTS, 1200);
                }
            }
            return;
        }

        // 贝拉套
        if (
                player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.KIRA_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.KIRA_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.KIRA_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.KIRA_BOOTS
        ){
            if (amount<4f){
                event.setAmount(0);
            }
            else {
                if (event.getSource() == DamageSource.FALL) {
                    event.setAmount(0);
                } else {
                    if (entity instanceof EntitySkeleton) {
                        event.setAmount(event.getAmount() * 0.25f);
                    } else if (entity instanceof EntityPlayer) {
                        event.setAmount(event.getAmount() * 0.5f);
                    } else {
                        event.setAmount(event.getAmount() * 0.7f);
                    }
                }
            }
        }

        if (!(entity instanceof EntityLivingBase)) return;
        EntityLivingBase attacker = (EntityLivingBase)entity;

        // 魔怔人ProPlusMax 破防
        if (attacker instanceof EntityBewilderedManProPlusMax && !player.isPotionActive(MobEffects.WEAKNESS)) {
            EntityUtil.ApplyBuff(player, MobEffects.WEAKNESS,0,3);
            player.sendMessage(new TextComponentTranslation("message.asoulworld.player_break_defense",null,null));
        }

        // 皇家骑士的剑 弹反
        if (player.getHeldItemMainhand().getItem() == ModItems.CAROL_FANS_SWORD && player.isPotionActive(ModPotions.COUNTER_ATTACK)){
            EntityUtil.ApplyBuff(player, MobEffects.RESISTANCE,4,1f);
            EntityUtil.TryRemoveGivenBuff(player,ModPotions.COUNTER_ATTACK);
            if (playerHealth>amount)
            {
                attacker.attackEntityFrom(DamageSource.causeMobDamage(player).setDamageBypassesArmor(),amount);
                EntityUtil.ApplyBuff(player, MobEffects.REGENERATION,2,2f);
                player.getCooldownTracker().setCooldown(ModItems.CAROL_FANS_SWORD, 15);
            }
            else
            {
                player.setHealth(2f);
                EntityUtil.ApplyBuff(player,MobEffects.SPEED,1,3f);
                EntityUtil.ApplyBuff(player,MobEffects.STRENGTH,1,3f);
                attacker.attackEntityFrom(DamageSource.causePlayerDamage(player).setDamageBypassesArmor(),amount>20?amount:20);
                player.getCooldownTracker().setCooldown(ModItems.CAROL_FANS_SWORD, 5);
            }
        }

        // 水晶蔷薇 受到致命伤时免疫该伤害
        // 将玩家传送至64格内的随机位置
        if (amount >= playerHealth){
            if (!player.getCooldownTracker().hasCooldown(ModItems.ITEM_CRYSTALL_ROSE)) {
                if (AsoulWorldUtils.getwhichItemStack3(player, s -> s.getItem() == ModItems.ITEM_CRYSTALL_ROSE)) {
                    event.setCanceled(true);
                    player.setHealth(10);
                    player.getCooldownTracker().setCooldown(ModItems.ITEM_CRYSTALL_ROSE, 1200);
                    EntityUtil.ApplyBuff(player, MobEffects.RESISTANCE, 100, 2);
                    EntityUtil.ApplyBuff(player, MobEffects.FIRE_RESISTANCE, 0, 20f);
                    EntityUtil.ApplyBuff(player, MobEffects.REGENERATION, 1, 15f);
                    EntityUtil.ApplyBuff(player, ModPotions.AS_FALL_IGNORE, 0, 15f);
                    for (int i = 0; i < 128; i++) {
                        if (ASEventHelper.teleportRandomly(player.posX, player.posY, player.posZ, event.getEntity().world, player)) {
                            Vec3d basePos = player.getPositionVector();
                            float range = 8;
                            List<EntityLivingBase> entities = event.getEntity().world.getEntitiesWithinAABB(EntityLivingBase.class, IDLGeneral.ServerAABB(basePos.addVector(-range, -range, -range), basePos.addVector(range, range, range)));
                            for (EntityLivingBase target : entities) {
                                if (target.isEntityEqual(event.getEntityLiving())) continue;
                                EntityUtil.ApplyBuff(target, MobEffects.WITHER, 2, 5f);
                            }
                            break;
                        }
                    }
                }
            }
        }

        //凋零 乃琳套
        if (
                player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem() == ModItems.EILEEN_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem() == ModItems.EILEEN_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem() == ModItems.EILEEN_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem() == ModItems.EILEEN_BOOTS
        ){
            attacker.addPotionEffect(new PotionEffect(MobEffects.WITHER, 100, 1));
            attacker.addPotionEffect(new PotionEffect(MobEffects.SLOWNESS, 100, 0));
            attacker.addPotionEffect(new PotionEffect(MobEffects.GLOWING, 200, 0));
            return;
        }

    }

    //玩家死亡事件
    @SubscribeEvent(priority = EventPriority.HIGHEST)
    public static void dianaPortectPlayer(LivingDeathEvent event)
    {
        EntityLivingBase living = event.getEntityLiving();
        Entity entity = event.getSource().getTrueSource();
        if (living.world.isRemote || !(living instanceof EntityPlayer) || living instanceof FakePlayer || event.isCanceled())
        {
            return;
        }
        EntityPlayer player = (EntityPlayer)living;

        if (
                player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem() == ModItems.EILEEN_HELMET &&
                player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem() == ModItems.EILEEN_CHESTPLATE &&
                player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem() == ModItems.EILEEN_LEGGINGS &&
                player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem() == ModItems.EILEEN_BOOTS
        ){
            if (entity instanceof EntityLiving){
                entity.attackEntityFrom(DamageSource.causePlayerDamage(player).setDamageBypassesArmor(), 20);
            }

            player.setItemStackToSlot(EntityEquipmentSlot.HEAD, ItemStack.EMPTY);
            player.setItemStackToSlot(EntityEquipmentSlot.CHEST, ItemStack.EMPTY);
            player.setItemStackToSlot(EntityEquipmentSlot.LEGS, ItemStack.EMPTY);
            player.setItemStackToSlot(EntityEquipmentSlot.FEET, ItemStack.EMPTY);

            player.setHealth(10);
            EntityUtil.ApplyBuff(player,MobEffects.RESISTANCE,100,2);
            player.sendMessage(new TextComponentTranslation("message.asoulworld.eileen_protect_player",null,null));
            event.setCanceled(true);
            return;
        }

        // Taffy
        // 时空传送
        if (!player.getCooldownTracker().hasCooldown(ModItems.TAFFY_HELMET) &&
            player.getItemStackFromSlot(EntityEquipmentSlot.HEAD).getItem()==ModItems.TAFFY_HELMET &&
            player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem()==ModItems.TAFFY_CHESTPLATE &&
            player.getItemStackFromSlot(EntityEquipmentSlot.LEGS).getItem()==ModItems.TAFFY_LEGGINGS &&
            player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem()==ModItems.TAFFY_BOOTS
        ){
            AsoulTimePower power = player.getCapability(CapabilityRegistryHandler.ASOUL_TIME_POWER, null);
            if (power != null){
                int[] posArray = power.getTime();
                if (posArray != null){
                    // 传送
                    player.setPositionAndUpdate(posArray[0], posArray[1], posArray[2]);
                }
            }
            // 免死
            player.sendMessage(new TextComponentTranslation("message.asoulworld.taffy_protect_player",null,null));
            player.setHealth(20);
            EntityUtil.ApplyBuff(player,MobEffects.RESISTANCE,100,2);
            EntityUtil.ApplyBuff(player,MobEffects.ABSORPTION,-5,0);
            EntityUtil.ApplyBuff(player, MobEffects.FIRE_RESISTANCE,0,60);
            event.setCanceled(true);
            // CD
            player.getCooldownTracker().setCooldown(ModItems.TAFFY_HELMET, 12000);
            player.getCooldownTracker().setCooldown(ModItems.TAFFY_CHESTPLATE, 12000);
            player.getCooldownTracker().setCooldown(ModItems.TAFFY_LEGGINGS, 12000);
            player.getCooldownTracker().setCooldown(ModItems.TAFFY_BOOTS, 12000);
            return;
        }

        //当典籍在冷却的时候不触发救赎
        if (player.getCooldownTracker().hasCooldown(ModItems.DIANA_CLASSICS))
        {
            return;
        }
        if (AsoulWorldUtils.consumeInventoryItem(living, s -> s.getItem() == ModItems.DIANA_CLASSICS, 1))
        {
            player.setHealth(20);
            EntityUtil.ApplyBuff(player,MobEffects.RESISTANCE,100,2);
            EntityUtil.ApplyBuff(player,MobEffects.ABSORPTION,-5,0);

            // CD
            player.getCooldownTracker().setCooldown(ModItems.DIANA_CLASSICS, 12000);
            player.sendMessage(new TextComponentTranslation("message.asoulworld.diana_protect_player",null,null));

            event.setCanceled(true);
        }

    }

}
